﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DownloadMag
{
    /// <summary>
    /// 下载任务队列控制器
    /// 功能：任务、任务队列控制
    /// 为 [下载控制器] 提供控制接口
    /// </summary>
    public class TaskListControl
    {
        public TaskListControl()
        {
            m_WaitingWorkThread = new List<DTaskConfig>();
            m_CompletedTaskList = new List<DTask>();
            m_RunningTaskList = new List<DTask>();
            m_StoppedTaskList = new List<DTask>();
            m_WaitingTaskList = new List<DTask>();
            m_FinishTaskQueue = new Queue<DTask>();

            m_MaxTask = 3;
        }

        #region 静态变量

        private static int s_Waittime = 5000;
        /// <summary>
        /// 错误重试等待时间
        /// </summary>
        public static int Waittime
        {
            get { return TaskListControl.s_Waittime; }
            set { TaskListControl.s_Waittime = value; }
        }

        #endregion

        #region 属性

        private List<DTask> m_WaitingTaskList;
        private List<DTask> m_RunningTaskList;
        private List<DTask> m_StoppedTaskList;
        private List<DTask> m_CompletedTaskList;
        private List<DTaskConfig> m_WaitingWorkThread;
        private Queue<DTask> m_FinishTaskQueue;
        private int m_MaxTask;

        /// <summary>
        /// 同时执行的最大任务数
        /// </summary>
        public int MaxTask
        {
            get { return m_MaxTask; }
            set { m_MaxTask = value; }
        }

        /// <summary>
        /// 等待的线程
        /// </summary>
        internal List<DTaskConfig> WaitingWorkThread
        {
            get { return m_WaitingWorkThread; }
            //set { m_WaitingWorkThread = value; }
        }
        /// <summary>
        /// 等待开始的任务队列
        /// </summary>
        internal List<DTask> WaitingTaskList
        {
            get { return m_WaitingTaskList; }
            //set { m_WaitingTaskList = value; }
        }
        /// <summary>
        /// 正在执行的任务队列
        /// </summary>
        internal List<DTask> RunningTaskList
        {
            get { return m_RunningTaskList; }
            //set { m_RunningTaskList = value; }
        }
        /// <summary>
        /// 处于停止状态的任务队列
        /// </summary>
        internal List<DTask> StoppedTaskList
        {
            get { return m_StoppedTaskList; }
            //set { m_StoppedTaskList = value; }
        }
        /// <summary>
        /// 已完成的任务队列
        /// </summary>
        internal List<DTask> CompletedTaskList
        {
            get { return m_CompletedTaskList; }
            //set { m_CompletedTaskList = value; }
        }

        #endregion

        /// <summary>
        /// 队列锁
        /// </summary>
        private readonly Object m_listLock = new Object();
        internal void AutoAdd(DTask task)
        {   // 任务状态变更事件在所有线程都有触发，此处需要同步
            lock (m_listLock)
            {
                switch (task.TaskState)
                {
                    case DTaskState.Aborted:
                        m_RunningTaskList.Remove(task);
                        m_StoppedTaskList.Remove(task);
                        m_CompletedTaskList.Remove(task);
                        m_WaitingTaskList.Remove(task);
                        break;
                    case DTaskState.Started:
                        if (!m_RunningTaskList.Contains(task))
                        {
                            m_RunningTaskList.Add(task);
                        }
                        m_StoppedTaskList.Remove(task);
                        m_CompletedTaskList.Remove(task);
                        m_WaitingTaskList.Remove(task);
                        break;
                    case DTaskState.Completed:
                        if (!m_CompletedTaskList.Contains(task))
                        {
                            m_CompletedTaskList.Add(task);
                        }
                        m_RunningTaskList.Remove(task);
                        break;
                    case DTaskState.Waiting:
                        if (!m_WaitingTaskList.Contains(task))
                        {
                            m_WaitingTaskList.Add(task);
                        }
                        m_StoppedTaskList.Remove(task);
                        m_CompletedTaskList.Remove(task);
                        m_RunningTaskList.Remove(task);
                        break;
                    default:
                        if (!m_StoppedTaskList.Contains(task))
                        {
                            m_StoppedTaskList.Add(task);
                        }
                        m_WaitingTaskList.Remove(task);
                        m_RunningTaskList.Remove(task);
                        break;
                }
            }
        }

        /// <summary>
        /// 结束任务
        /// </summary>
        /// <param name="task"></param>
        internal void FinishTask(DTask task)
        {
            m_FinishTaskQueue.Enqueue(task);
        }
        /// <summary>
        /// 回收已完成的线程
        /// </summary>
        internal void TaskDispose()
        {
            // 释放所有下载线程
            while (m_FinishTaskQueue.Count > 0)
            {
                DTask dt = m_FinishTaskQueue.Dequeue();
                if (dt.TaskState == DTaskState.Completed || dt.TaskState == DTaskState.Stopped)
                {
                    dt.TaskConfigs.Clear();
                }
            }
        }

        internal DTaskConfig[] GetWaitingWorkThread()
        {
            return m_WaitingWorkThread.ToArray();
        }

        internal void AddWaitingWorkThread(DTaskConfig dtc)
        {
            dtc.Waittime = TaskListControl.Waittime;
            m_WaitingWorkThread.Add(dtc);
        }

        internal void ReStartWaitingWorkThread(DTaskConfig dtc)
        {
            m_WaitingWorkThread.Remove(dtc);
            dtc.ReStart();
        }

        /// <summary>
        /// 启动所有任务
        /// </summary>
        public void Start()
        {
            while (m_StoppedTaskList.Count > 0)
            {
                StartTask(m_StoppedTaskList[0]);
            }
        }
        /// <summary>
        /// 停止所有任务
        /// </summary>
        public void Stop()
        {
            m_WaitingWorkThread.Clear();
            while (m_WaitingTaskList.Count > 0)
            {
                StopTask(m_WaitingTaskList[0]);
            }
            while (m_RunningTaskList.Count > 0)
            {
                StopTask(m_RunningTaskList[0]);
            }
        }

        /// <summary>
        /// 清空控制器内容
        /// </summary>
        public void Clear()
        {
            m_WaitingWorkThread.Clear();
            m_CompletedTaskList.Clear();
            m_RunningTaskList.Clear();
            m_StoppedTaskList.Clear();
            m_WaitingTaskList.Clear();
            m_FinishTaskQueue.Clear();
        }

        internal void AutoNext()
        {
            while (m_WaitingTaskList.Count > 0 && (m_MaxTask <= 0 || m_RunningTaskList.Count < m_MaxTask))
            {
                DTask task = m_WaitingTaskList[0];
                task.Start();
            }
        }

        internal void StartTask(DTask task)
        {
            if (task.TaskState == DTaskState.Stopped || task.TaskState == DTaskState.Failed || task.TaskState == DTaskState.Aborted)
            {
                if (m_MaxTask <= 0 || m_RunningTaskList.Count < m_MaxTask)
                {
                    task.Start();
                }
                else
                {
                    task.ReadyToStart();
                }
            }
        }
        internal void ReStartTask(DTask task)
        {
            task.ResetTaskData();
            StartTask(task);
        }
        internal void StopTask(DTask task)
        {
            if (task.TaskState == DTaskState.Started || task.TaskState == DTaskState.Waiting)
            {
                task.Stop();
            }
        }
        /// <summary>
        /// 移除任务（取消任务）
        /// </summary>
        /// <param name="task"></param>
        /// <param name="type">[1]删除未完成下载的文件|[2]删除已下载的文件|[其他]不删除文件</param>
        internal void RemoveTask(DTask task, int type)
        {
            // 取消任务[自动从任务列表中移除]
            task.Abort();

            // 删除未下载的文件？删除已下载的文件？
            task.Remove(type);
        }
    }
}
